package com.haiyou.dc.suanfa.demo1;

import com.haiyou.dc.util.TimeTool;

/**
 * 斐波那契数列
 * 前面两个数相加=后面那个数
 * 0 1 1 2 3 5 8 13
 * 求第n个数等于多少
 */
public class TestFib {

    /**
     * 递归实现，前面两个数相加=后面那个数
     *
     * @param n
     * @return
     */
    public static long fib1(int n) {
        if (n <= 1) {
            return n;
        }
        return fib1(n - 1) + fib1(n - 2);
    }

    /**
     *
     * @param n
     * @return
     */
    public static long fib2(int n) {
        if (n <= 1) {
            return n;
        }
        int first = 0;
        int second = 1;
        for (int i = 0; i < n - 1; i++) {
            int sum = first + second;
            first = second;
            second = sum;
        }
        return second;
    }

    public static void main(String[] args) {
        int n = 60;
//        TimeTool.check("fib1", () -> {
//            System.out.println(fib1(n));
//        });
        TimeTool.check("fib2", () -> {
            System.out.println(fib2(n));
        });
    }

}
